package com.tianma.upload.uploadjartest.controller;


import com.upload.spring.boot.chooser.UploadChooer;
import com.upload.spring.boot.server.UploadCustomizer;
import com.upload.spring.boot.type.UploadType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

/**
 * @author lgc
 * @createDate 2020/7/28 - 18:17
 */
@Controller
public class FileController {
    Logger log =  LoggerFactory.getLogger(this.getClass());

    @Autowired
    UploadChooer uploadChooer;

    @GetMapping("/uploads")
    public ModelAndView upload() {
        System.out.println("进来了");
        return new ModelAndView("upload");
    }
    @ResponseBody
    @PostMapping("/upload")
    String uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String originalFileName = file.getOriginalFilename();
        originalFileName = originalFileName.substring(0, originalFileName.indexOf(".")) + "-" + System.currentTimeMillis() + originalFileName.substring(originalFileName.indexOf("."));

        //上传方式选择
        UploadCustomizer uploadCustomizer = uploadChooer.chooseType(UploadType.LOCAL);
        if (uploadCustomizer==null){
            return "该上传方式还未开启";
        }
        String upload = uploadCustomizer.upload(file.getBytes(), originalFileName);
        return upload;
    }
}
